package com.springboot_gradrecruit.common;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.util.Collections;
import java.util.List;

/**
 * @author zr
 */
@Data
public class PageResponse<T> {

    //1.总条数
    private Long total;

    //2.总页数
    private Long pages;

    //3.集合
    private List<T> data;

    //
    public static <PO,VO> PageResponse<VO> of(Page<PO> page, Class<VO> voClass){
        PageResponse<VO> pageResponse = new PageResponse<>();
        //1.总条数
        pageResponse.setTotal(page.getTotal());
        //2.总页数
        pageResponse.setPages(page.getPages());
        //3.集合
        List<PO> records = page.getRecords();
        if(CollUtil.isEmpty(records)){
            pageResponse.setData(Collections.emptyList());
            return pageResponse;
        }
        //4.转VO
        pageResponse.setData(BeanUtil.copyToList(records, voClass));
        return pageResponse;

    }

    /**
     * 封装分页数据，连表查询
     */
    public static <PO, VO> PageResponse<VO> of(Page<PO> page, List<VO> listVO) {
        PageResponse<VO> pageResponse = new PageResponse<>();

        Long len = (long) listVO.size();

        // 1. 设置总条数
        pageResponse.setTotal(len);

        Long pages = (len%page.getSize()==0 ? len/page.getSize():len/page.getSize()+1);

        // 2. 设置总页数
        pageResponse.setPages(pages);

        // 4. 设置数据列表
        if (listVO.isEmpty()) {
            pageResponse.setData(Collections.emptyList());
        } else {
            pageResponse.setData(listVO);
        }

        return pageResponse;
    }




}
